jQuery.validator.addMethod(
		"newRoom", 
		function(value) { 
			return $(".listRoomName").filter(
				function() { return $(this).text() == $.trim(value); }).size() == 0;		
		}, 
		"Room already exists!"
);

$().ready(function() {

	FB.init( {
		appId: '126564364026625',
		xfbml : false
	});
	
	$("#createRoomForm").validate({
		submitHandler: function(form) {
			$.post("GetRooms",
				facebookURL({
					type: "createRoom",
					gameSize: $("#roomSize").val(),
					gameName: $("#roomName").val()
				}),
				function(data) {
					var status = $(data).find("status").text();
					if (status == "created") {
						window.location.href = "http://delta-tomcat-vm.cs.tau.ac.il:40767//game.html";
					} else { // db-problem or no-user
						jAlert("We are having some problems, please try again later", "Info");
					}
				}
			);
		},
		rules: {
			roomName: {
				required: true,
				minlength: 2,
				newRoom: true
			},
			roomSize: {
				required: true,
				range: [2, 6]
			}
		},
		messages: {
			roomName: {
				required: "Please enter a room name",
				minlength: "at least 2 characters",
				newRoom: "Room already exists!"
			},
			roomSize: {
				required: "Please enter room size",
				range: "Must be between 2-6"
			}
		}
	});
	
	$('#createRoomForm input').keypress(function(e) {
		if (e.which == 13) {
			$('#createRoomForm').submit();
			return false;
		}
	});
	
});


function processUserOptions() {
	$('#userDetails').modal();
	getUserDetails();	
}

function processHallOfFame() {
	$('#hallOfFame').modal();
	getHallOfFame();
}

function repeatGetRooms() {
	getRooms();
	setTimeout(repeatGetRooms, 1000);
}
repeatGetRooms();


///////////// facebook shit

function postOnWall() {
	FB.login(handleSessionResponse, { perms:'publish_stream'	});
}

function handleSessionResponse(response) {
	if (!response.session) {
		return;
	} else {
		$.get("GetUser",
				facebookURL({ type: "postOnWall" }),
				function(data) {
					jAlert("Posted on your wall", "Info");
				}
			);
	}
}
